<?php

namespace App\Support\Helpers;

use Illuminate\Support\Str as IlluminateStr;

class StringHelper
{
    /**
     * generate random text
     *
     * @param int $length     length of the generated text
     * @param string $pool    character pool
     *
     * @return string  generated random text
     */
    public static function quickRandom($length = 6, $pool = null)
    {
        if (empty($pool)) {
            return IlluminateStr::quickRandom($length);
        }

        $repeats = ceil($length / strlen($pool));
        return substr(str_shuffle(str_repeat($pool, $repeats)), 0, $length);
    }

    /**
     * decode json in a safe way. by 'safe', we mean that false will be safely
     * returned if given json text is invalid.
     *
     * @param string $json the <i>json</i> string being decoded.
     * @param bool $assoc  when <b>TRUE</b>, returned objects will be converted into associative arrays.
     *
     * @return mixed       the decoded value or false on error.
     */
    public static function safeJsonDecode($json, $assoc = true)
    {
        $decoded = json_decode($json, $assoc);
        if ($decoded === null  && json_last_error() !== JSON_ERROR_NONE) {
            return false;
        } else {
            return $decoded;
        }
    }

    public static function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for ($i=0;$i<$length;$i++) {
            $str.=$strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
        return $str;
    }

    /**
     * 判断字符串是否存在
     * @param $string
     * @param $find
     * @return bool
     */
    public static function strexists($string, $find)
    {
        return !(strpos($string, $find) === false);
    }
}
